/**
 * 2025/01/01 - 2025/12/31
 */
package com.snail.server.database.engine.ddl.operation;

import com.snail.server.database.engine.ddl.model.index.IndexMo;
import com.snail.server.database.engine.ddl.service.DDLService;
import com.snail.starter.commons.exception.BizException;
import com.snail.server.database.engine.error.DatabaseEngineErrorCode;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.stream.Collectors;

/**
 * @author zgadmin
 * @date 2025/8/29 14:56
 */
@Slf4j
public abstract class AbstractDDLOperation implements IDDLOperation {

    public static final String BLANK = " ";

    @Resource
    DDLService ddlService;

    public abstract String ignoreKeyword(String keyword);

    public boolean execute(String sql) {
        return ddlService.execute(sql);
    }

    public String indexToSql(IndexMo index) {
        return indexToSql(null, index);
    }

    public String indexToSql(String tableName, IndexMo index) {
        StringBuilder fieldSql = new StringBuilder();
        if (null != tableName && !"".equals(tableName)) {
            fieldSql.append("CREATE").append(BLANK);
        }
        switch (index.getType()) {
            case INDEX:
                fieldSql.append("INDEX");
                break;
            case UNIQUE_INDEX:
                fieldSql.append("UNIQUE INDEX");
                break;
            default:
                throw BizException.of(DatabaseEngineErrorCode.NOT_SUPPORT_INDEX_TYPE, new Object[]{index.getType().getDesc()});
        }
        fieldSql.append(BLANK)
                .append(ignoreKeyword(index.getName()));
        if (null != tableName && !"".equals(tableName)) {
            fieldSql.append(BLANK).append("ON").append(BLANK).append(ignoreKeyword(tableName));
        }
        fieldSql.append(BLANK)
                .append(
                        index.getIndexFields().stream()
                                .map(indexField -> ignoreKeyword(indexField.getFieldName()) + BLANK + indexField.getOrderBy().getValue())
                                .collect(Collectors.joining(",", "(", ")"))
                );
        return fieldSql.toString();
    }

}